package com.wanmait.schedule.controller;

import com.github.pagehelper.PageInfo;
import com.wanmait.schedule.entity.*;
import com.wanmait.schedule.service.PermissionService;
import com.wanmait.schedule.service.RolePermissionService;
import com.wanmait.schedule.service.RoleService;
import com.wanmait.schedule.shiro.ShiroRealm;
import com.wanmait.schedule.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 角色权限表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-12-05
 */
@RestController
@RequestMapping("/manage/rolePermission")
@RequiresPermissions("manage:role_permission")
public class RolePermissionController {

    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RolePermissionService rolePermissionService;

    //根据角色显示角色与权限对应列表   分页，条件搜索
    @PostMapping("list")
    public AjaxResult list(@RequestBody RolePermission rolePermission, Integer pageNum){
        PageInfo<Role> pageInfo = rolePermissionService.list(rolePermission,pageNum);
        return AjaxResult.success(pageInfo);
    }

    //根据角色id查找该角色所对应的权限
    @GetMapping("listByRoleId")
    public AjaxResult listByRoleId(Integer id){
        List<Permission> roles = rolePermissionService.listByRoleId(id);
        return AjaxResult.success(roles);
    }

    //根据角色Id和权限ID数组，修改角色所拥有权限
    @PostMapping("update")
    public AjaxResult update(Integer id,@RequestBody Integer[] ids){
        /*System.out.println(Arrays.toString(ids));*/
        rolePermissionService.update(id,ids);
        //清除缓存
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
        shiroRealm.getAuthorizationCache().clear();

        return AjaxResult.success();
    }

}
